package com.liuche.pictureserver.process;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.liuche.pictureserver.common.exception.BizException;
import com.liuche.pictureserver.common.exception.ErrorCode;
import com.liuche.pictureserver.enums.ProcessEnum;
import com.liuche.pictureserver.pojo.ProcessModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 责任链处理器
 *
 * @author liuche
 */
@Slf4j
@Component
public class ProcessController implements CommandLineRunner {
    /**
     * 责任链信息
     */
    private static final Map<String, ProcessTemplate> PROCESS_HANDLER_MAP = new ConcurrentHashMap<>();

    /**
     * 加载所有责任链信息
     *
     * @param args 参数
     */
    @Override
    public void run(String... args) {
        List<ProcessEnum> processEnumList = ProcessEnum.getAll();
        if (CollUtil.isEmpty(processEnumList)) {
            return;
        }
        for (ProcessEnum processEnum : processEnumList) {
            ProcessTemplate bean;
            try {
                bean = SpringUtil.getBean(processEnum.getBeanName());
            } catch (Exception e) {
                log.error("加载责任链信息失败，请检查[{}]是否存在", processEnum.getBeanName());
                continue;
            }
            PROCESS_HANDLER_MAP.put(processEnum.getCode(), bean);
        }
    }

    /**
     * 执行责任链
     *
     * @param processEnum 责任链
     * @return 结果
     */
    public <T extends ProcessModel> ProcessContext<T> runProcess(ProcessEnum processEnum, ProcessContext<T> context) {
        ProcessTemplate processTemplate = PROCESS_HANDLER_MAP.get(processEnum.getCode());
        if (processTemplate == null) {
            throw new BizException(ErrorCode.SYSTEM_ERROR);
        }
        return processTemplate.process(context);
    }
}
